package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴
 * @version V1.0
 * @Description
 * @Package com.itheima.controller
 * @date 2021/11/28 9:08
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;
    /**
     * 手机号登录
     * @param response
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Map map, HttpServletResponse response) {

        String telephone = (String) map.get("phoneNumber");
        String validateCode = (String)map.get("validateCode");

        try {
            // 验证码校验
            String code = jedisPool.getResource().get(telephone + RedisConstant.SENDTYPE_LOGIN);
            if (!Objects.equals(code, validateCode)) {
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            }

            // 登录之前查询是否是会员，不是就自动注册
            Member member = memberService.findByTelephone(telephone);
            if (member == null) {
                //创建member对象，设置参数
                member = new Member();
                member.setName(telephone);
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                member.setStatus(0);
                memberService.saveInfo(member);
            }
           if (member.getStatus()==0){

                // 向客户端写入Cookie，内容为用户手机号
                Cookie cookie = new Cookie("telephone", telephone);
                cookie.setPath("/");    // 所有页面都是可见的cookie
                cookie.setMaxAge(30 * 60); //设置有效时长
                response.addCookie(cookie);

                // 将会员信息保存到Redis，使用手机号作为key，保存时长为30分钟
                String json = JSON.toJSONString(member);
                jedisPool.getResource().setex(telephone, 30 * 60, json);
                return new Result(true, MessageConstant.LOGIN_SUCCESS);
            }else{
                return new Result(false, MessageConstant.LOGIN_FAIL);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.LOGIN_FAIL);
        }
    }
}
